package com.symaster.backups.frame.element.table;

import com.symaster.common.swing.util.SwingUtil;

import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import java.awt.*;

/**
 * @author yinmiao
 * @version 2024/2/5
 */
public class TableUI extends ComponentUI {

    private JComponent c;

    public static ComponentUI createUI(JComponent c) {
        TableUI tableUI = new TableUI();
        tableUI.c = c;
        return tableUI;
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        super.paint(g, c);

        if (c instanceof Table table && table.getLayout() instanceof TableLayout tableLayout) {
            final int headHeight = table.getHeadHeight();
            final boolean verticalDivider = table.isVerticalDivider();
            final boolean horizontalDivider = table.isHorizontalDivider();

            Insets insets = c.getInsets();
            Graphics graphics = g.create(insets.left, insets.top, c.getWidth() - insets.right - insets.left, c.getHeight() - insets.bottom - insets.top);
            SwingUtil.antialiasingOn((Graphics2D) graphics);

            if (horizontalDivider) {
                graphics.setColor(new Color(194, 194, 194));
                for (Component component : c.getComponents()) {
                    Rectangle bounds = component.getBounds();
                    graphics.drawLine(0, bounds.height + bounds.y, c.getWidth(), bounds.height + bounds.y);
                }
            }

            int xOffset = 0;
            for (int i = 0; i < tableLayout.getColumnCount(); i++) {
                int columnWidth = tableLayout.getColumnWidth(i);
                String columnLabel = tableLayout.getColumnLabel(i);

                if (horizontalDivider) {
                    graphics.setColor(new Color(194, 194, 194));
                    graphics.drawLine(xOffset + columnWidth + 1, 0, xOffset + columnWidth + 1, headHeight);
                }

                Graphics graphics1 = graphics.create(xOffset, 0, columnWidth, headHeight);
                SwingUtil.antialiasingOn((Graphics2D) graphics1);

                int i1 = SwingUtilities.computeStringWidth(graphics.getFontMetrics(), columnLabel);

                graphics1.setColor(new Color(0, 0, 0, 255));
                graphics1.drawString(columnLabel,
                        Math.round((columnWidth / 2f) - (i1 / 2f)),
                        Math.round(headHeight / 2f + graphics1.getFont().getSize() / 2f));
                xOffset += columnWidth + (horizontalDivider ? 1 : 0);

                graphics1.dispose();
            }

            if (verticalDivider) {
                graphics.setColor(new Color(194, 194, 194));
                graphics.drawLine(0, headHeight, c.getWidth(), headHeight);
            }

            graphics.dispose();
        }
    }
}
